function idat = fsb_normalize(idat,sandbox,what)

% FSB : Normalize trials voxel by voxel to average brain intensity
%
% EXAMPLE:
% idat = fsb_normalize(idat,sandbox,what)
%
% INPUT:
% idat:             4-D image data
% sandbox:          Sandbox Experiment struct
% what:             sessions(5)
%                   runs(4)
%                   trials(3)
%
% OUTPUT:
% idat:             Normalized 4D image data
%
% CALLED BY:
% FSB.m
%
% NOTES:
%
% Copyright Steffen Stoewer 28/11/07
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License: GNU GPL, no express or implied warranties
% 
% $Revision 1.0
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

intrial = sandbox.intrial;
imean = mean(idat,4);

%~~~~~~~~~~~~~~~~~~~~~~
% Create waitbar string
%~~~~~~~~~~~~~~~~~~~~~~
switch what
    case 3
        waitstr = 'Normalizing trials to average trial intensity';
    case 4
        waitstr = 'Normalizing runs to average run intensity';
    case 5
        waitstr = 'Normalizing sessions to average session intensity';
end

%~~~~~~~~~~~~~~~~~~~~~~
% Do actual normalization
%~~~~~~~~~~~~~~~~~~~~~~
if max(intrial(:,what))>1;

    h = waitbar(0,waitstr);
    mean_idat = single(imean);

    for x = 1:max(sandbox.intrial(:,what));

        waitbar(x/max(sandbox.intrial(:,what)));
        scanind = find (sandbox.intrial(:,what)==x);
        idat_red = single(idat(:,:,:,scanind));
        voxel_ind = mean(idat_red,4);
        voxel_corr = mean_idat./voxel_ind;
        idat_red = idat_red.* (repmat(voxel_corr,[1 1 1 size(idat_red,4)]));
        idat(:,:,:,scanind) = int16(idat_red);

    end;

    close(h);
end
